<template>
	<view class="main">
		<view class="roomlist">
			<view class="roomlist__item" v-for="item in roomList" 
				:class="screenVideoId == item.id? 'isScreen':''"
				v-show="screenVideoId == null || screenVideoId == item.id"
				@click="handleUser(item)"
			>
				<!-- 用户头像 -->
				<!-- v-if="!(!item.videoMuted || item.isScreenShareEnabled)" -->
				<view class="user-icon-box"
					v-if="!(!item.videoMuted || item.isScreenShareEnabled)"
					:loading="!item.isJoin"
				>
					<u-avatar :src="configs.avatarUrl+'/' + item.id+'.jpg'"></u-avatar>
				</view>
				
				<!-- 视频容器 -->
				<view class="roomlist__item__video" 
				v-show="!item.isScreenShareEnabled"
				 :id="item.id + '_video'"></view>
				<!-- 桌面分享容器 -->
				<view class="roomlist__item__screen" 
				v-show="item.isScreenShareEnabled"
				 :id="item.id + '_screen'"></view>
				<!-- 音频容器 -->
				<view class="roomlist__item__audio"  :id="item.id + '_audio'"></view>
				
				<!-- 用户名称 -->
				<view class="user-box" v-if="!screenVideoId">
					<view class="cuIcon cuIcon-voicefill  "
					:class="item.muted?'text-red':'text-green'"
					></view>
					<view class="user-name">{{item.name}}</view>
				</view>
				<!-- 退出全屏按钮 -->
				<view class="isQuitScreen" 
				@click.stop="handleVideoScreen(item,item.isScreenShareEnabled || item.videoMuted)" 
				v-show="screenVideoId">退出全屏</view>
				<!-- 打开全屏按钮 -->
				<view class="showScreen cuIcon cuIcon-full text-white" 
				@click.stop="handleVideoScreen(item,item.isScreenShareEnabled || item.videoMuted)"
				v-show="(!item.videoMuted || item.isScreenShareEnabled)&&!screenVideoId"></view>
				
			</view>
		</view>
		<view class="tool-bar" v-if="!screenVideoId">
			<!-- 声音控制 -->
			<view class="cuIcon cuIcon-voicefill" @click="handleMute(!Ismicrophone && !Ispermission)"
			 :class="myRoom.muted?'text-red':'text-white'"></view>
			<!-- 视频控制 -->
			<view class="cuIcon cuIcon-recordfill" @click="handleCloseVideo" :class="myRoom.videoMuted?'text-red':'text-white'"></view>
			<!-- 桌面分享 -->
			<view class="cuIcon cuIcon-newsfill" @click="handleShareScreen" :class="myRoom.isScreenShareEnabled?'text-red':'text-white'"></view>
			<!-- 聊天 -->
			<!-- <view class="cuIcon cuIcon-commentfill text-white "
			 :class="isChatRed?'isDot':''"
			 @click="handleChat()"></view> -->
			<!-- 操作 -->
			<view class="cuIcon cuIcon-moreandroid text-white" @click="handleAboutRoom()"></view>
		</view>
		
		<!-- 聊天窗体 -->
		<!-- <u-popup :show="isShowChat" :round="10" 
			closeable
			closeOnClickOverlay @close="isShowChat = false"
		>
			<chat @sendMessage="sendMessage" :messageList="messageList" ref="livekitChat" />
		</u-popup> -->
		<!-- 房间操作 -->
		<u-popup :show="isShowAbout" :round="10"
			closeOnClickOverlay @close="isShowAbout = false"
		>
			<aboutRoom :roomInfo="roomInfo" :Ismicrophone="Ismicrophone" 
			:Ispermission="Ispermission"
			@handleDisableMic="handleDisableMic" @handleAddUser="handleAddUser"
			@closeMetting = "handleConfirmClose" />
		</u-popup>
		
		<!-- 人员操作 -->
		<u-popup :show="isShowOpUser" :round="10"
			closeOnClickOverlay @close="isShowOpUser = false"
		>
			<operateUser :userInfo="userInfo" 
			@handleUserMic="handleUserMic"
			@handlekickOutMeet="handlekickOutMeet"
			 :Ispermission="Ispermission"
			 />
		</u-popup>
		
		<!-- 选人弹窗 -->
		<!-- <u-popup :show="isShowUser" :round="10">
			<inviteBook ref="userSelectRef" @close = "isShowUser = false" 
			@inviteLivekit="handleAgainQuickMeet" />
		</u-popup> -->
		
	</view>
</template>
<script>
import {
		mapGetters
	} from 'vuex';
import core from "@/core"
import store from '@/store'
import * as API_liveKit from '@/api/livekit'
import { livekit_main_implementation } from './js/livekit_main_implementation'
// import chat from './components/chat.vue'
import aboutRoom from './components/aboutRoom.vue'
import operateUser from './components/operateUser.vue'
// import inviteBook from './inviteBook.vue'
import { stopCallBack, handleCallMeetAgain } from './js/common'
import { messageBody } from './js/messageData'
import {
    livekit_main,
    stopMeetting,
    closeMeettingCamera,
    closeMeettingMic,
    shareScreen
} from './js/index'

import { createMessage } from './js/common'
import configs from '@/config/config'
export default {
	components: {
		// chat,
		aboutRoom,
		// inviteBook,
		operateUser
	},
	data() {
		return{
			configs:configs,
			isChatRed: false,
			isShowUser:false,
			isShowOpUser:false,
			mediaObj:{},
			isVideo:false,
			theme: core.style,
			roomTag:null,
			isShowChat:false,
			isShowAbout:false,
			meetType:'order',
			roomInfo: {},
			memberParams: {},
			messageList: [],
			roomList:[],
			screenVideoId:null,
			roomToken:'',
			microphone:true,
			camera:false,
			time:'',
			store:store,
			formData:{},
			userInfo:{},//被操作人员详情
			myRoom: {
				id: store.getters.user ? store.getters.user.id : '',
				name: store.getters.user ? store.getters.user.name : '',
				isJoin: true,
				videoMuted: true,
				muted: true,
				isScreenShareEnabled: false
			},
			allRoomList: [
				{ id: store.getters.user ? store.getters.user.id : '',
				name: store.getters.user ? store.getters.user.name : ''}
			],
		}
	},
	computed:{
		...mapGetters(['user']),
		// 判断是否是房主
		Ispermission(){
			return this.user.id == this.roomInfo.uid
		},
		Ismicrophone(){
			return this.roomInfo.muted
		}
	},
	onLoad(option){
		// uni.$on('inviteLivekit', (group) => {
		// 	this.handleAgainQuickMeet(group)
		// })
		if(option.type == 'quick'){
			this.meetType = 'quick'
			let list = JSON.parse(option.group);
			console.log(list);
			this.handleQuickMeet(list)
		}else if(option.type == 'liveadd'){
			this.formData = JSON.parse(option.addForm);
			this.handleJoinMeet();
		}else if(option.type == 'booking'){
			let params = JSON.parse(option.params);
			this.handleOrderMeet(params);
		}else if(option.type == 'metting'){
			this.handleJoinMeet(option.tag);
		}
	},
	methods:{
		//打开关闭音频
		handleMute(t){
			// if(t) return core.toast('房间已禁言');
			
			closeMeettingMic(2, (muted) => {
				this.myRoom.muted = !muted
				this.roomList = this.roomList.map(item => {
					if (item.id == this.myRoom.id) {
						item.muted = !muted
					}
					return item
				})
			})
		},
		 // 打开关闭视频
		handleCloseVideo(){
			closeMeettingCamera((muted) => {
				this.myRoom.videoMuted = !muted
				this.roomList = this.roomList.map(item => {
					if (item.id == this.myRoom.id) {
						item.videoMuted = !muted
					}
					return item
				})
			})
		},
		// 
		handleShareScreen(){
			shareScreen()
		},
		// 处理快速会议
		async handleQuickMeet(members){
			const resp = await this.createMeet()  // 创建会议
			if (!resp.data) return
			this.roomInfo = {
				uid: store.getters.user.id,
				name: store.getters.user.name,
				title: '',  // 会议室名称加上"的快速会议"作为会议标题
				description: '',  // 会议室名称加上"的快速会议"作为会议描述
				tag: resp.data,
				muted: false
			}
			this.roomTag = resp.data  // 保存会议标签
			this.roomList.push(this.myRoom)  // 将会议室添加到会议室列表中
			this.memberParams = {}
			members.forEach(item => {
				this.memberParams[item.id] = item.name  // 保存成员信息
				this.roomList.push({
					id: item.id,
					name: item.name,
					isJoin: false,
					videoMuted: true,
					muted: true,
					isScreenShareEnabled: false  // 将成员添加到会议室列表中，并设置一些初始状态
				})
			})
			let tokenParams = {
				roomTag: this.roomTag,
				name:this.user.name
			}
			const roomData = await API_liveKit.getRoomToken(tokenParams)  // 获取房间token
			if (roomData.code == 200) {
				this.roomToken = roomData.data  // 保存房间token
				this.microphone = true  // 启用麦克风
				livekit_main_implementation(this)  // 执行livekit_main_implementation函数
			}
		},
		// 创建一个异步函数createMeet，接收一个参数params
		async createMeet(params){
			uni.showLoading({
				title: '正在创建会议...',
				mask: true
			});
			const resp = await API_liveKit.createMeet(params) //  创建房间
			uni.hideLoading();
			if (resp.code == 200 && resp.data) {
				return resp
			} else {
				return core.toast('会议创建失败，请联系管理员')
			}
		},
		handleAgainQuickMeet(members){
			this.isShowUser=false;
			this.memberParams = {}
			members.forEach(item => {
				this.memberParams[item.id] = item.name  // 保存成员信息
				this.roomList.push({
					id: item.id,
					name: item.name,
					isJoin: false,
					videoMuted: true,
					muted: true,
					isScreenShareEnabled: false  // 将成员添加到会议室列表中，并设置一些初始状态
				})
			})
			let params = {
				roomTag: this.roomTag,
				member: this.memberParams
			}
			handleCallMeetAgain(params)
		},
		// 处理加入会议的逻辑
		async handleJoinMeet(roomTag){
			// pauseAudio();
			const roomResp = await this.handleGetRoomInfo(this.formData.roomTag || roomTag)
			if (roomResp.data.dueTime) this.meetType = 'order'
			else this.meetType = 'quick'
			if (!roomResp) return false
			this.roomInfo = roomResp.data
			this.screenVideoId = null;
			if (this.formData.roomTag || roomTag) { // 如果有传入房间号或者传入的房间号存在
				this.roomTag = this.formData.roomTag || roomTag // 设置房间号
				this.roomList.push(this.myRoom) // 将我的房间加入到房间列表中
				let params = {
					roomTag: this.roomTag,
					name:this.user.name
				}
				const roomData = await API_liveKit.getRoomToken(params) // 获取房间token
				if (roomData.code == 200) { // 如果获取成功
					this.roomToken = roomData.data // 将token保存到数据中
					this.microphone = false // 默认关闭麦克风
					this.camera = false // 默认关闭摄像头
					if (this.formData.microphone) this.microphone = this.formData.microphone // 如果表单中有麦克风状态，则设置麦克风状态
					if (this.formData.camera) this.camera = this.formData.camera // 如果表单中有摄像头状态，则设置摄像头状态
					livekit_main_implementation(this) // 实施主要的会议逻辑
					this.formData = {} // 清空表单数据
				}
			} else {
				this.toast('会议号不能为空')
			}
		},
		// 预约会议
		async handleOrderMeet(params){
			let resp = await this.createMeet(params)
			if (!resp.data) return
			const roomResp = await handleGetRoomInfo(resp.data)
			// console.log(roomResp)
			if (roomResp && roomResp.code == 200) {
				const messageData = {
					meetType: 'order',
					roomList: [{ id: this.user.id, name: this.user.name }],
					time: '00:00:00',
					roomTag: roomResp.data.tag,
					roomInfo: roomResp.data
				}
				createMessage(messageData)
				this.formData = {}
				// data.isShowRoomInfoLayer = true
				this.roomGetInfo = roomResp.data
			}
		},
		handleAboutRoom(){
			this.isShowAbout = true;
		},
		handleChat(){
			this.isChatRed = false;
			this.isShowChat = true;
			this.$nextTick(()=>{
				this.scrollBottom();
			})
		},
		handleVideoScreen(el,isVideo){
			if (isVideo) return;
			this.screenVideoId ? this.screenVideoId = null : this.screenVideoId = el.id
		},
		// 窗口关闭弹窗
		handleConfirmClose(){
			this.isShowAbout = false
			let opList = ['离开会议'];
			// 房主
			if(this.Ispermission) opList.push('结束会议')
			uni.showActionSheet({
				itemList: opList,
				success: async res=>{
					console.log(res)
					console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
					if(res.tapIndex == 0){
						stopMeetting(() => {
							stopCallBack(this)
							// playAudio(5)
						})
					}else{
						await this.finishMeet()
						stopMeetting(() => {
							stopCallBack(this)
						})
					}
				},
				fail: function (res) {
					console.log(res.errMsg);
				}
			});
		},
		handleUser(userInfo){
			if(this.screenVideoId) return;
			if(this.user.id == userInfo.id) return;
			if(!this.Ispermission) return;
			
			this.userInfo = {...userInfo};
			this.isShowOpUser = true;
		},
		handleUserMic({type,userInfo}){
			this.userInfo[type] = !this.userInfo[type];
			let uid = this.userInfo.id;
			let mediaType = this.userInfo[type];
			if(type=='muted') mediaType? this.closeMemberAudio(uid) : this.openMemberAudio(uid);
			else mediaType? this.closeMemberCamera(uid):this.openMemberCamera(uid)
		},
		async finishMeet(){ // 结束会议
			const params = {
				roomTag: this.roomTag
			}
			await API_liveKit.finishMeet(params)
		},
		// 禁言
		async handleDisableMic(){
			this.isShowAbout = false;
			const muted = this.roomInfo.muted
			const params = {
				roomTag: this.roomTag
			}
			if (muted) {
				await API_liveKit.setMicOn(params) // 解除禁言
				this.roomInfo.muted = !this.roomInfo.muted
			} else {
				await API_liveKit.setMicOff(params) // 禁言
				this.roomInfo.muted = !this.roomInfo.muted
			}

		},
		// 再次邀请
		handleAddUser(){
			this.isShowAbout = false;
			// this.naviTo('livekit/inviteBook?group='+JSON.stringify(this.roomList) + '&add=add');
			this.isShowUser = true
			this.$nextTick(()=>{
				this.$refs.userSelectRef.selectUser(this.roomList);
			})
		},
		// 发送聊天消息
		sendMessage(text){
			let params = {
				roomTag: this.roomTag,
				content: text
			}
			API_liveKit.sendMessage(params).then(resp => {
				if (resp.code == 200) {
					const message = messageBody({ sender: this.roomTag, name: this.user.name, receiver: this.user.id, content: text })
					this.messageList.push(message)
					this.$nextTick(() => {
						this.$refs.livekitChat.clearEditor();
						this.scrollBottom();
					})
				}
			})
		},
		// 发送消息或接受消息之后，消息滚到底部
		scrollBottom(){
			this.$refs.livekitChat&&this.$refs.livekitChat.scrollBottom()
		},
		// 获取房间详情
		async handleGetRoomInfo(roomTag){
			let params = {
				roomTag: roomTag
			}
			const resp = await API_liveKit.getRoomInfo(params)
			if (resp.code == 200) {
				return resp
			} else {
				this.toast('房间不存在')
				return false
			}
		},
		closeMemberAudio(id){
			let params = {
				roomTag: this.roomTag,
				uid: id
			}
			API_liveKit.setMemberMicOff(params).then(resp => {
				if (resp.code == 200) {
					this.roomList = this.roomList.map(item => {
						if (item.id == id) {
							item.muted = true
						}
						return item
					})
				}
			})
		},
		openMemberAudio(id){
			let params = {
				roomTag: this.roomTag,
				uid: id
			}
			API_liveKit.setMemberMicOn(params).then(resp => {
				if (resp.code == 200) {
					this.roomList = this.roomList.map(item => {
						if (item.id == id) {
							item.muted = false
						}
						return item
					})
				}
			})
		},
		closeMemberCamera(id){
			let params = {
				roomTag: this.roomTag,
				uid: id
			}
			API_liveKit.setMemberCamOff(params).then(resp => {
				if (resp.code == 200) {
					this.roomList = this.roomList.map(item => {
						if (item.id == id) {
							item.videoMuted = true
						}
						return item
					})
				}
			})
		},
		openMemberCamera(id){
			let params = {
				roomTag: this.roomTag,
				uid: id
			}
			API_liveKit.setMemberCamOn(params).then(resp => {
				if (resp.code == 200) {
					this.roomList = this.roomList.map(item => {
						if (item.id == id) {
							item.videoMuted = false
						}
						return item
					})
				}
			})
		},
		// 移除会议
		handlekickOutMeet(useritem){
			this.isShowOpUser = false;
			return core.confirm('确定要将'+useritem.name+'移出会议吗?', '移出会议', async () => {
				if (useritem.isJoin) {
					let params = {
						roomTag: this.roomTag,
						uid: useritem.id
					}
					API_liveKit.kickOutMeet(params)
				} else {
					let uid = useritem.id
					this.roomList = this.roomList.filter(item => {
						if (item.id != uid) {
							return item
						}
					})
				}
			})
		}
	}
}
</script>



<style lang="scss" scoped>
// 操作栏
.tool-bar{
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	display: flex;
	justify-content: space-around;
	align-items: center;
	.cuIcon{
		font-size: 35rpx;
		background-color: #9e9ea1;
		border-radius: 50%;
		width: 80rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}
}
.roomlist{
	padding-top: 10rpx;
	display: flex;
	flex-wrap: wrap;
	// flex-direction: f;
	justify-content: flex-start;
}
.roomlist__item{
	width: 48%;
	height: 350rpx;
	margin-left: 10rpx;
	background-color: #000;
	margin-top: 10rpx;
	transition: .1s;
	position: relative;
	
	.user-icon-box{
		position: absolute !important;
		z-index: 1;
		display: flex;
		width: 70px;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		justify-content: center;
		align-items: center;
		height: inherit;
		height: 70px;
		border: 3px solid #f8f8f8;
		box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
		border-radius: 50%;
		overflow: hidden;
	}
	.roomlist__item__video,.roomlist__item__screen{
		display: flex;
		width: 100%;
		height: 100%;
		overflow: hidden !important;
		flex-direction: column;
		justify-content: center;
		video{
			width: 100% !important;
		}
	}
	.user-box{
		position: absolute !important;
		left:5rpx;
		bottom:3rpx;
		background-color: #f8f8f8;
		padding:5rpx 15rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		font-size: 24rpx;
		.user-name{
			margin: 0 5rpx;
		}
	}
	.isQuitScreen{
		position: absolute !important;
		left:50%;
		transform: translate(-50%, 0);
		bottom:100rpx;
		background-color: #515353;
		opacity: .8;
		padding:5rpx 15rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		font-size: 34rpx;
		color: #fff;
	}
	.showScreen{
		position: absolute !important;
		top: 20rpx;
		right: 20rpx;
		font-size: 34rpx;
	}
}
.isScreen{
	width: 100vw !important;
	height: 100vh !important;
}
.isDot{
	position: relative;
	&::after{
		position: absolute;
		content:'';
		width: 25rpx;
		height: 25rpx;
		border-radius: 50%;
		background-color: orangered;
		top: -2rpx;
		right: 2rpx;
	}
}

</style>
